package saer.send.now.operations;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import saer.send.now.channel.Channel;

public class Download implements IOperation {
    public static final String  OP_CODE = "dl";

    private static final Logger log     = Logger.getLogger(Download.class.getName());

    @Override
    public void exec(Map<String, Channel> channelStore, String id, HttpServletRequest req, HttpServletResponse resp) {
        log.log(Level.FINEST, "Got DOWNLOAD request, req:{0}", req);
        if (id == null) {
            log.log(Level.WARNING, "Id is missing, req:{0}", req);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        Channel channel = channelStore.get(id);
        if (channel == null) {
            log.log(Level.WARNING, "Could not find channel, req:{0}, id:{1}", new Object[]{req, id});
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        try {
            channel.download(resp.getOutputStream());
        } catch (IOException e) {
            log.log(Level.WARNING, "Download request failed, req:{0}, id:{1}", new Object[]{req, id});
            throw new RuntimeException("Download request failed", e);
        }
    }
}
